package cn.oi.klittle.era.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.telephony.SmsMessage
import android.text.TextUtils
import android.util.Log

///添加权限：<uses-permission android:name="android.permission.RECEIVE_SMS" />
object KSmsCodeUtils {
    /**
     * 上下文
     */
    private var context: Context? = null

    /**
     * 利用广播，接受短信
     */
    private var smsReceiver: BroadcastReceiver? = null
    private var filter2: IntentFilter? = null

    /**
     *
     * @param context 上下文
     */
    fun init(context: Context?) {
        this.context = context
        filter2 = IntentFilter()
        filter2!!.addAction("android.provider.Telephony.SMS_RECEIVED")
        filter2!!.priority = Int.MAX_VALUE
    }

    /**
     * 启动广播，利用广播接受短信
     * from 短信来源手机号，该号码一般都是+86开头
     * message 短信内容
     *
     */
    fun start(callback:(from:String,message:String)->Unit) {
        /**
         * 广播，获取短信
         */
        smsReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                Log.e("test", "intent     " + intent);
                val objs = intent.extras!!["pdus"] as Array<Any>?
                for (obj in objs!!) {
                    val pdu = obj as ByteArray
                    val sms = SmsMessage.createFromPdu(pdu)
                    // 短信的内容
                    val message = sms.messageBody
                    Log.e("test", "message     " + message);
                    // 获取短信的手机号码，该号码一般都是+86开头
                    val from = sms.originatingAddress
                    if (!TextUtils.isEmpty(from)) {
                        callback?.let { it(from!!,message) }
                    }
                }
            }
        }
        context!!.registerReceiver(smsReceiver, filter2)
    }

    /**
     * 关闭广播
     */
    fun end() {
        context!!.unregisterReceiver(smsReceiver)
    }
}